﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MusicAcademy
{
    public partial class frmSessions : Form
    {
        public long RegisterID = -1;
        public long TermID = -1;
        public long StudentID = -1;
        public long TeacherID = -1;
        public long recordID = -1;
        private int ClassID = -1;

        public frmSessions()
        {
            InitializeComponent();
        }

        private bool isValid()
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;
            bool valid = true;

            com.Connection = con;
            com.CommandType = CommandType.Text;
            con.Open();

            if (RegisterID == -1)
                valid = Globals.SetError(txtRegister);
            else
                Globals.SetValid(txtRegister);

            if (txtDate.IsValidDate() == false)
                valid = Globals.SetError(txtDate);
            else
                Globals.SetValid(txtDate);

            if (txtTime.Text.IndexOf("_") >= 0 || Globals.IsValidTime(txtTime.Text) == false)
                valid = Globals.SetError(txtTime);
            else
                Globals.SetValid(txtTime);

            if (ClassID == -1)
                valid = Globals.SetError(txtClass);
            else
                Globals.SetValid(txtClass);

            com.CommandText = "SELECT ID FROM Holiday WHERE academyID=@academyID AND date=@date";
            com.Parameters.AddWithValue("@academyID", Program.academyID);
            com.Parameters.AddWithValue("@date", txtDate.Text);

            dreader = com.ExecuteReader();
            if (dreader.HasRows)
            {
                valid = Globals.SetError(txtDate);
                MessageBox.Show("این تاریخ به عنوان یک روز تعطیل برای آموزشگاه ثبت شده است .", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            dreader.Close();
            com.Parameters.Clear();

            return valid;
        }
        private void RefreshGrid()
        {
            int stateSearch;

            if (cmbStateSearch.SelectedIndex != -1)
                stateSearch = (int)cmbStateSearch.SelectedValue;
            else
                stateSearch = -1;

            fullSessionTableAdapter.Fill(musicAcademyDataSet.FullSession, stateSearch, RegisterID, TermID, txtTeacherSearch.Text, txtStudentSearch.Text, StudentID, TeacherID, txtToolNameSearch.Text, fromDate.Text, toDate.Text);

        }
        private void frmSessions_Load(object sender, EventArgs e)
        {
             if (UserManager.HasAccess(this.Name, "View") == false)
            {
                MessageBox.Show("شما اجازه ی دیدن این فرم را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            RefreshGrid();
            // TODO: This line of code loads data into the 'musicAcademyDataSet.SessionStatus' table. You can move, or remove it, as needed.
            this.sessionStatusTableAdapter.Fill(this.musicAcademyDataSet.SessionStatus);
            cmbStateSearch.SelectedIndex = -1;
        }

        private void fromDate_Leave(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void toDate_Leave(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtStudentSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtTeacherSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtToolNameSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void btnClearSearch_Click(object sender, EventArgs e)
        {
            fromDate.Text = "";
            toDate.Text = "";
            txtTeacherSearch.Text = "";
            txtStudentSearch.Text = "";
            txtToolNameSearch.Text = "";
            cmbStateSearch.SelectedIndex = -1;

            TermID = -1;
            StudentID = -1;
            TeacherID = -1;
            if (RegisterID == -1)
                txtRegister.Text = "";
            RefreshGrid();
        }

        private void btnSelectRegister_Click(object sender, EventArgs e)
        {
            ListOfRegisters r = new ListOfRegisters();
            if (r.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtRegister.Text = r.StudentName + " در کلاس " + r.ToolName + " - استاد " + r.TeacherName;
                RegisterID = r.SelectedID;
                RefreshGrid();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;

            com.Connection = con;
            com.CommandType = CommandType.Text;

            if (isValid() == false)
                return;

            if (recordID == -1)
            {
                if (UserManager.HasAccess(this.Name, "Insert") == false)
                {
                    MessageBox.Show("شما اجازه ی اضافه کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                com.CommandText = "INSERT INTO Session (date, time, classID, status, registerID, grade, academyID, creator, createDate) VALUES (@date, @time, @classID, @status, @registerID, @grade, @academyID, @creator, @createDate); SELECT TOP 1 ID FROM Session ORDER BY ID DESC";
                com.Parameters.AddWithValue("@date", txtDate.Text);
                com.Parameters.AddWithValue("@time", txtTime.Text);
                com.Parameters.AddWithValue("@classID", ClassID);
                com.Parameters.AddWithValue("@status", cmbState.SelectedValue);
                com.Parameters.AddWithValue("@registerID", RegisterID);
                com.Parameters.AddWithValue("@grade", txtGrade.Text);
                com.Parameters.AddWithValue("@academyID", Program.academyID);
                com.Parameters.AddWithValue("@creator", Program.userID);
                com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());

                con.Open();
                dreader = com.ExecuteReader();
                dreader.Read();
                recordID = Convert.ToInt32(dreader["ID"]);
                dreader.Close();
                com.Parameters.Clear();
                con.Close();

                btnDelete.Enabled = true;

                RefreshGrid();
            }
            else
            {
                if (UserManager.HasAccess(this.Name, "Update") == false)
                {
                    MessageBox.Show("شما اجازه ی ویرایش کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                com.CommandText = "UPDATE Session SET date=@date, time=@time, classID=@classID, status=@status, grade=@grade, lastEditor=@lastEditor, editDate=@editDate WHERE ID=@SessionID";
                com.Parameters.AddWithValue("@date", txtDate.Text);
                com.Parameters.AddWithValue("@time", txtTime.Text);
                com.Parameters.AddWithValue("@classID", ClassID);
                com.Parameters.AddWithValue("@status", cmbState.SelectedValue);
                com.Parameters.AddWithValue("@grade", txtGrade.Text);
                com.Parameters.AddWithValue("@lastEditor", Program.userID);
                com.Parameters.AddWithValue("@editDate", Globals.Get10CharDate());
                com.Parameters.AddWithValue("@SessionID", recordID);

                con.Open();
                com.ExecuteNonQuery();
                com.Parameters.Clear();
                con.Close();

                RefreshGrid();
            }

            MessageBox.Show("ذخیره شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnClass_Click(object sender, EventArgs e)
        {
            ListOfClasses c = new ListOfClasses();
            if (c.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ClassID = c.SelectedID;
                txtClass.Text = c.ClassNumber;
            }
        }

        private void cmbStateSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void grdSession_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            Globals.SetValid(txtRegister);
            Globals.SetValid(txtDate);
            Globals.SetValid(txtTime);
            Globals.SetValid(txtClass);
            txtRegister.Text = grdSession.Rows[e.RowIndex].Cells["studentName"].Value.ToString() + " در کلاس " +
                             grdSession.Rows[e.RowIndex].Cells["toolName"].Value.ToString() + " - استاد " +
                             grdSession.Rows[e.RowIndex].Cells["teacherName"].Value.ToString();
            txtGrade.Text = grdSession.Rows[e.RowIndex].Cells["grade"].Value.ToString();
            txtDate.Text= grdSession.Rows[e.RowIndex].Cells["date"].Value.ToString();
            txtTime.Text = grdSession.Rows[e.RowIndex].Cells["time"].Value.ToString();
            txtClass.Text = grdSession.Rows[e.RowIndex].Cells["classNumber"].Value.ToString();
            cmbState.SelectedValue = grdSession.Rows[e.RowIndex].Cells["status"].Value;

            recordID = Convert.ToInt32(grdSession.Rows[e.RowIndex].Cells["ID"].Value);
            RegisterID = Convert.ToInt32(grdSession.Rows[e.RowIndex].Cells["_registerID"].Value);
            ClassID = Convert.ToInt32(grdSession.Rows[e.RowIndex].Cells["_classID"].Value);

            btnDelete.Enabled = true;
        }

        private void ClearForm()
        {
            txtRegister.Text = "";
            txtGrade.Text = "";
            txtDate.Text = "";
            txtTime.Text = "";
            txtClass.Text = "";
            cmbState.SelectedIndex = -1;
            RegisterID = -1;
            TermID = -1;
            StudentID = -1;
            TeacherID = -1;
            recordID = -1;
            ClassID = -1;

            Globals.SetValid(txtRegister);
            Globals.SetValid(txtDate);
            Globals.SetValid(txtTime);
            Globals.SetValid(txtClass);
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
            RefreshGrid();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();

            if (UserManager.HasAccess(this.Name, "Delete") == false)
            {
                MessageBox.Show("شما اجازه ی حذف کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (MessageBox.Show("آیا از حذف این رکورد اطمینان دارید ؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                com.Connection = con;
                com.CommandType = CommandType.Text;

                com.CommandText = "DELETE FROM Session WHERE ID=@ID";
                com.Parameters.AddWithValue("@ID", recordID);

                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                ClearForm();
                RefreshGrid();

                MessageBox.Show("حذف شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtGrade_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void chkContainsSearch_CheckedChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void btnClearStateSearch_Click(object sender, EventArgs e)
        {
            cmbStateSearch.SelectedIndex = -1;
        }
    }
}
